package com.example.android01;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int PERMISSION_REQUEST_CODE = 1001;

    private MqttPublisher publisher;
    private TextView temperatureValue, humidityValue, lightValue, currentValue, voltageValue, powerValue;
    private TextView temperatureStatus, humidityStatus, lightStatus, currentStatus, voltageStatus, powerStatus;
    private TextView connectionStatus;
    private Button refreshBtn; // 新增：刷新按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initUIComponents();
        checkPermissions();
    }

    private void initUIComponents() {
        temperatureValue = findViewById(R.id.temperatureValue);
        humidityValue = findViewById(R.id.humidityValue);
        lightValue = findViewById(R.id.lightValue);
        currentValue = findViewById(R.id.currentValue);     // 电流对应字段改为 I
        voltageValue = findViewById(R.id.voltageValue);   // 电压对应字段改为 U
        powerValue = findViewById(R.id.powerValue);       // 功率对应字段改为 W

        temperatureStatus = findViewById(R.id.temperatureStatus);
        humidityStatus = findViewById(R.id.humidityStatus);
        lightStatus = findViewById(R.id.lightStatus);
        currentStatus = findViewById(R.id.currentStatus);
        voltageStatus = findViewById(R.id.voltageStatus);
        powerStatus = findViewById(R.id.powerStatus);

        connectionStatus = findViewById(R.id.connectionStatus);

        // 初始化刷新按钮
        refreshBtn = findViewById(R.id.refreshBtn);
        refreshBtn.setOnClickListener(v -> sendRefreshCommand());
    }

    private void checkPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PERMISSION_REQUEST_CODE);
        } else {
            initMQTTClient();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initMQTTClient();
            } else {
                Toast.makeText(this, "网络权限被拒绝，无法连接MQTT服务器", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void initMQTTClient() {
        // 添加用户名和密码参数
        publisher = new MqttPublisher(
                "tcp://broker.emqx.io:1883",
                "fhasohasfsfsdsdfas",
                0,
                "your_username",    // 替换为实际MQTT用户名
                "your_password");   // 替换为实际MQTT密码

        publisher.setMessageHandler((topic, message) -> {
            runOnUiThread(() -> {
                connectionStatus.setText("已连接");
                parseSensorData(message);
            });
        });

        publisher.setConnectionListener(new MqttPublisher.ConnectionListener() {
            @Override
            public void onConnected() {
                runOnUiThread(() -> {
                    connectionStatus.setText("已连接");
                    Toast.makeText(MainActivity.this, "MQTT连接成功", Toast.LENGTH_SHORT).show();
                    publisher.publish("/broker/mqtt/Limo_s", "Hello, MQTT!");
                });
            }

            @Override
            public void onConnectionLost(Throwable cause) {
                runOnUiThread(() -> {
                    connectionStatus.setText("已断开");
                    Toast.makeText(MainActivity.this, "MQTT连接已断开: " + cause.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });

        publisher.connect();
        publisher.subscribe("/broker/mqtt/Limo");
    }

    private void sendRefreshCommand() {
        if (publisher != null && publisher.isConnected()) {
            try {
                publisher.publish("/broker/mqtt/Limo_s", "env:get");
                Toast.makeText(this, "已发送刷新命令", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Log.e(TAG, "发送刷新命令失败", e);
                Toast.makeText(this, "刷新命令发送失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "MQTT未连接，无法发送刷新命令", Toast.LENGTH_SHORT).show();
        }
    }

    private void parseSensorData(String message) {
        try {
            JSONObject root = new JSONObject(message);

            // 解析 power 子对象
            JSONObject power = root.optJSONObject("power");
            double powerW = power.optDouble("W", 0);
            double currentI = power.optDouble("I", 0);
            double voltageU = power.optDouble("U", 0);

            // 解析 env 子对象
            JSONObject env = root.optJSONObject("env");
            double temperature = env.optDouble("tem", 0);
            double humidity = env.optDouble("hum", 0);
            double lightLux = env.optDouble("lux", 0);

            // 设置数值显示
            temperatureValue.setText(String.format("%.1f℃", temperature));
            humidityValue.setText(String.format("%.1f%%", humidity));
            lightValue.setText(String.format("%.1fLx", lightLux));
            currentValue.setText(String.format("%.1fA", currentI));
            voltageValue.setText(String.format("%.1fV", voltageU));
            powerValue.setText(String.format("%.1fW", powerW));

            // 设置状态检查（注意参数顺序调整：current对应I，voltage对应U，power对应W）
            setStatus(temperatureStatus, temperature, 18, 26);
            setStatus(humidityStatus, humidity, 30, 70);
            setStatus(lightStatus, lightLux, 300, 1000);
            setStatus(currentStatus, currentI, 0, 20);       // 电流阈值假设为0-20A
            setStatus(voltageStatus, voltageU, 220, 240);     // 电压阈值假设为220-240V
            setStatus(powerStatus, powerW, 0, 1000);          // 功率阈值假设为0-1000W

        } catch (JSONException e) {
            Log.e(TAG, "解析JSON数据出错: " + message, e);
            Toast.makeText(this, "数据格式错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void setStatus(TextView statusView, double value, double min, double max) {
        if (value < min) {
            statusView.setText("偏低");
            statusView.setTextColor(getResources().getColor(android.R.color.holo_red_light));
        } else if (value > max) {
            statusView.setText("偏高");
            statusView.setTextColor(getResources().getColor(android.R.color.holo_orange_light));
        } else {
            statusView.setText("正常");
            statusView.setTextColor(getResources().getColor(android.R.color.holo_green_light));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (publisher != null) {
            publisher.disconnect();
        }
    }
}